package com.hk.websocket.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hk.auth.SpaceUserPermissionConstant;
import com.hk.auth.service.SpaceUserAuthService;
import com.hk.model.entity.Picture;
import com.hk.model.entity.Space;
import com.hk.model.vo.user.UserVO;
import com.hk.service.PictureService;
import com.hk.service.SpaceService;
import com.hk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 *
 * @author huangkun
 * @date 2025/2/11 19:16
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private SpaceUserAuthService userAuthService;
    @Override
    public boolean beforeHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response,@NonNull WebSocketHandler wsHandler,@NonNull Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest servletRequest){
            HttpServletRequest httpServletRequest = servletRequest.getServletRequest();
            String pictureId = httpServletRequest.getParameter("pictureId");
            if (StrUtil.isBlank(pictureId)){
                log.error("缺少图片Id参数");
                return false;
            }
            Picture picture = pictureService.getById(pictureId);
            if (picture == null){
                log.error("图片不存在");
                return false;
            }
            UserVO userVO = userService.getCurrentUser(httpServletRequest);
            if (userVO == null){
                log.error("用户未登录");
                return false;
            }
            Space space = spaceService.getById(picture.getSpaceId());
            //校验当前用户是否对该图片有编辑权限
            List<String> permissionList = userAuthService.getPermissionList(space, userVO);
            if(!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)){
                log.error("用户没有编辑权限");
                return false;
            }
            attributes.put("user",userVO);
            attributes.put("pictureId",Long.valueOf(pictureId));
        }
        return true;
    }

    @Override
    public void afterHandshake(@NonNull ServerHttpRequest request,@NonNull ServerHttpResponse response,@NonNull WebSocketHandler wsHandler, Exception exception) {

    }
}
